/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
 */

package com.tcredit.client.sdk.smartu;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import org.apache.cordova.ConfigXmlParser;
import org.apache.cordova.CordovaInterfaceImpl;
import org.apache.cordova.CordovaPreferences;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewImpl;
import org.apache.cordova.PluginEntry;
import org.apache.cordova.PluginManager;
import org.apache.cordova.engine.SystemWebChromeClient;
import org.apache.cordova.engine.SystemWebView;
import org.apache.cordova.engine.SystemWebViewClient;
import org.apache.cordova.engine.SystemWebViewEngine;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

public class MainNewActivity extends Activity implements WebView.OnClickListener
{
    public static String TAG = "MainNewActivity";
    private SendDataTask sDataTask = null;
    // The webview for our app
    private CordovaWebView appView;
    private TextView backTv;
    private TextView closeTv;
    private TextView titleTv;
    private ImageView imageView;

    //    private ProgressBar progressBar1;
    protected boolean keepRunning = true;
    protected CordovaPreferences preferences;
    protected String launchUrl;
    protected ArrayList<PluginEntry> pluginEntries;
    protected CordovaInterfaceImpl cordovaInterface;

    private Map<String, String> titleMap = new HashMap<String, String>();

    private SystemWebView webView;

    //        private String host = "http://test.jin.dlymoney.com";
//    private String host = "http://test.yzj.tcredit.com";
//    private String host ="http://172.19.160.92:8080";
    private String host = "https://yzj.tcredit.com";
    private String userId;
    private String cid;
    private String sign;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        loadConfig();

        // enable Cordova apps to be started in the background
        Bundle extras = getIntent().getExtras();
        userId = UUID.randomUUID().toString();
        cid = "";
        sign = "";
        if (extras != null && extras.containsKey("uid")) {
            userId = extras.getString("uid");
        }
        if (extras != null && extras.containsKey("cid")) {
            cid = extras.getString("cid");
        }
        if (extras != null && extras.containsKey("sign")) {
            sign = extras.getString("sign");
        }
        if (extras != null && extras.containsKey("url")) {
            host = extras.getString("url");
        }
//        String url = "";
//        if (extras != null && extras.containsKey("url")) {
//            url = extras.getString("url");
//        }
//        launchUrl = url +"home/iqiyi/index?uid="+userId+"&sign="+sign;
//        launchUrl = url +"index?uid="+userId+"&sign="+sign;
        launchUrl = host + "/home/index?uid=" + userId + "&sign=" + sign + "&cid="+ cid;
//        launchUrl = "https://yzj.tcredit.com/home/iqiyi/index?uid="+userId+"&sign="+sign;
//        launchUrl = "http://172.19.163.208:9001/iqiyi_client/_contents.html";
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

        super.onCreate(savedInstanceState);

        setContentView(R.layout.toolbar_layout);

//        progressBar1 = (ProgressBar) findViewById(R.id.progressBar1);

        webView = findViewById(R.id.cordovaWebView);

        //禁用缓存
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

        SystemWebViewEngine systemWebViewEngine = new SystemWebViewEngine(webView, preferences);

        webView.setWebChromeClient(new SystemWebChromeClient(systemWebViewEngine) {

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (!TextUtils.isEmpty(title)) {
                    String[] strs = title.split("\\.");
                    if (strs.length <= 3 && !title.startsWith("http")) {
                        if (title.length() > 5) {
                            title = title.substring(0, 4) + "...";
                        }
                        String currentUrl = view.getUrl();
                        String cleanUrl = currentUrl.replaceAll("\\#(.*)?", "");
                        titleMap.put(cleanUrl, title);
                        titleTv.setText(title);
                    }
                }
            }

//            @Override
//            public void onProgressChanged(WebView view, int newProgress) {
//                super.onProgressChanged(view, newProgress);
//                if (newProgress == 100) {
//                    progressBar1.setVisibility(View.GONE);
//                } else {
//                    progressBar1.setVisibility(View.VISIBLE);
//                    progressBar1.setProgress(newProgress);
//                }
//            }
        });


        webView.setWebViewClient(new SystemWebViewClient(systemWebViewEngine) {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                String cleanUrl = url.replaceAll("\\#(.*)?", "");
                String str = titleMap.get(cleanUrl);
                if (!TextUtils.isEmpty(str)) {
                    titleTv.setText(str);
                }
            }
        });


        appView = new CordovaWebViewImpl(systemWebViewEngine);
        backTv = findViewById(R.id.textView);
        closeTv = findViewById(R.id.textView2);
        titleTv = findViewById(R.id.textView3);
        imageView = findViewById(R.id.img);
        backTv.setOnClickListener(this);
        closeTv.setOnClickListener(this);
        imageView.setOnClickListener(this);

        cordovaInterface = makeCordovaInterface();
        if (savedInstanceState != null) {
            cordovaInterface.restoreInstanceState(savedInstanceState);
        }
        init();

        //todo 原来的代码
//        sDataTask = new SendDataTask(userId,cid,getApplicationContext());
//        sDataTask.execute((Void) null);
//        appView.clearCache();
//        loadUrl(launchUrl);

        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE)!=PackageManager.PERMISSION_GRANTED){
                requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},1000);
            }else {
                initurl(userId, cid);
            }
        }else {
            initurl(userId, cid);
        }

    }

    private void initurl(String userId, String cid) {
        sDataTask = new SendDataTask(userId,cid,getApplicationContext());
        sDataTask.execute((Void) null);
        appView.clearCache();
        loadUrl(launchUrl);
    }

    /**
     * Load the url into the webview.
     */
    public void loadUrl(String url) {
        // If keepRunning
        this.keepRunning = preferences.getBoolean("KeepRunning", true);
        appView.loadUrlIntoView(url, true);
    }

    protected void init() {
        if (!appView.isInitialized()) {
            appView.init(cordovaInterface, pluginEntries, preferences);
        }
        cordovaInterface.onCordovaInit(appView.getPluginManager());

        // Wire the hardware volume controls to control media if desired.
        String volumePref = preferences.getString("DefaultVolumeStream", "");
        if ("media".equals(volumePref.toLowerCase(Locale.ENGLISH))) {
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
        }
    }

    protected void loadConfig() {
        ConfigXmlParser parser = new ConfigXmlParser();
        parser.parse(this);
        preferences = parser.getPreferences();
        preferences.setPreferencesBundle(getIntent().getExtras());
        launchUrl = parser.getLaunchUrl();
        pluginEntries = parser.getPluginEntries();
    }

    protected CordovaInterfaceImpl makeCordovaInterface() {
        return new CordovaInterfaceImpl(this) {
            @Override
            public Object onMessage(String id, Object data) {
                // Plumb this to CordovaActivity.onMessage for backwards compatibility
                return MainNewActivity.this.onMessage(id, data);
            }
        };
    }

    @Override
    public void onClick(View v) {
        final MainNewActivity me = this;
        int i = v.getId();
        if (i == R.id.textView || i == R.id.img) {
            if (appView.canGoBack()) {
                appView.getEngine().goBack();
            } else {
                me.finish();
            }
        } else if (i == R.id.textView2) {
            me.finish();
        }

    }

    public Object onMessage(String id, Object data) {
        if ("onReceivedError".equals(id)) {
            JSONObject d = (JSONObject) data;
            try {
                this.onReceivedError(d.getInt("errorCode"), d.getString("description"), d.getString("url"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else if ("exit".equals(id)) {
            finish();
        }
        return null;
    }

    public void onReceivedError(final int errorCode, final String description, final String failingUrl) {
        final MainNewActivity me = this;

        // If errorUrl specified, then load it
        final String errorUrl = preferences.getString("errorUrl", null);
        if ((errorUrl != null) && (!failingUrl.equals(errorUrl)) && (appView != null)) {
            // Load URL on UI thread
            me.runOnUiThread(new Runnable() {
                public void run() {
                    me.appView.showWebPage(errorUrl, false, true, null);
                }
            });
        }
        // If not, then display error dialog
        else {
            final boolean exit = !(errorCode == WebViewClient.ERROR_HOST_LOOKUP);
            me.runOnUiThread(new Runnable() {
                public void run() {
                    if (exit) {
                        me.appView.getView().setVisibility(View.GONE);
                        me.displayError("Application Error", description + " (" + failingUrl + ")", "OK", exit);
                    }
                }
            });
        }
    }

    /**
     * Display an error dialog and optionally exit application.
     */
    public void displayError(final String title, final String message, final String button, final boolean exit) {
        final MainNewActivity me = this;
        me.runOnUiThread(new Runnable() {
            public void run() {
                try {
                    AlertDialog.Builder dlg = new AlertDialog.Builder(me);
                    dlg.setMessage(message);
                    dlg.setTitle(title);
                    dlg.setCancelable(false);
                    dlg.setPositiveButton(button,
                            new AlertDialog.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    if (exit) {
                                        finish();
                                    }
                                }
                            });
                    dlg.create();
                    dlg.show();
                } catch (Exception e) {
                    finish();
                }
            }
        });
    }
    /**
     * Called when the system is about to start resuming a previous activity.
     */
    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "Paused the activity.");

        if (this.appView != null) {
            // CB-9382 If there is an activity that started for result and main activity is waiting for callback
            // result, we shoudn't stop WebView Javascript timers, as activity for result might be using them
            boolean keepRunning = this.keepRunning || this.cordovaInterface.activityResultCallback != null;
            this.appView.handlePause(keepRunning);
        }
    }

    /**
     * Called when the activity receives a new intent
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //Forward to plugins
        if (this.appView != null)
            this.appView.onNewIntent(intent);
    }

    /**
     * Called when the activity will start interacting with the user.
     */
    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "Resumed the activity.");

        if (this.appView == null) {
            return;
        }
        // Force window to have focus, so application always
        // receive user input. Workaround for some devices (Samsung Galaxy Note 3 at least)
        this.getWindow().getDecorView().requestFocus();

        this.appView.handleResume(this.keepRunning);
    }

    /**
     * Called when the activity is no longer visible to the user.
     */
    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "Stopped the activity.");

        if (this.appView == null) {
            return;
        }
        this.appView.handleStop();
    }

    /**
     * Called when the activity is becoming visible to the user.
     */
    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "Started the activity.");

        if (this.appView == null) {
            return;
        }
        this.appView.handleStart();
    }

    /**
     * The final call you receive before your activity is destroyed.
     */
    @Override
    public void onDestroy() {
        Log.d(TAG, "CordovaActivity.onDestroy()");
        super.onDestroy();

        if (this.appView != null) {
            appView.handleDestroy();
        }
    }

    @SuppressLint("NewApi")
    @Override
    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
        // Capture requestCode here so that it is captured in the setActivityResultCallback() case.
        cordovaInterface.setActivityResultRequestCode(requestCode);
        super.startActivityForResult(intent, requestCode, options);
    }

    /**
     * Called when an activity you launched exits, giving you the requestCode you started it with,
     * the resultCode it returned, and any additional data from it.
     *
     * @param requestCode The request code originally supplied to startActivityForResult(),
     *                    allowing you to identify who this result came from.
     * @param resultCode  The integer result code returned by the child activity through its setResult().
     * @param intent      An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        Log.d(TAG, "Incoming Result. Request code = " + requestCode);
        super.onActivityResult(requestCode, resultCode, intent);
        cordovaInterface.onActivityResult(requestCode, resultCode, intent);
    }



    protected void onSaveInstanceState(Bundle outState) {
        cordovaInterface.onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    /**
     * Called by the system when the device configuration changes while your activity is running.
     *
     * @param newConfig The new device configuration
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (this.appView == null) {
            return;
        }
        PluginManager pm = this.appView.getPluginManager();
        if (pm != null) {
            pm.onConfigurationChanged(newConfig);
        }
    }

    /**
     * Called by the system when the user grants permissions
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        try
        {
            cordovaInterface.onRequestPermissionResult(requestCode, permissions, grantResults);
        }
        catch (JSONException e)
        {
            Log.d(TAG, "JSONException: Parameters fed into the method are not valid");
            e.printStackTrace();
        }

        switch (requestCode){
            case 1000:
                if (grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    initurl(userId, cid);
                }else {
                    initurl(userId, cid);
                }
                break;
        }

    }

//    @Override
//    public void onBackPressed() {
//       if(null != webView){
//           if(webView.canGoBack()){
//               webView.goBack();
//           }else{
//              super.onBackPressed();
//           }
//       }
//    }



}
